# coding=UTF-8
from django.shortcuts import render_to_response
from django.forms import Textarea,FileField,CharField,Form,ModelForm
from django.http import HttpResponseRedirect, HttpResponseForbidden,HttpResponseNotFound,HttpResponse
from upload.models import UserFile,FileBin
import os,logging,urllib
from django.utils.encoding import force_unicode,smart_str
from google.appengine.ext import db
from google.appengine.api import users
from google.appengine.api import memcache
from django.core.urlresolvers import reverse
FILE_MAX=100
import sys

class FileForm(ModelForm):
    file = FileField()    
    class Meta:
        model = UserFile
        exclude = ("creationDate",'mimetype','size','author','name','comment')

def albumentry(request):
    if request.method == 'POST':
       
        file = request.FILES['file']   
        userfile = UserFile(  mimetype=request.META['CONTENT_TYPE'],
                                author = users.get_current_user(),
                                size = file.size,
                                name=file.name,
                                comment=request.REQUEST.get('comment',''))
        
        userfile.save() 
        filebin = FileBin(userfile=userfile, bin=db.Blob(file.read()))
        filebin.save()
        file.close()
        if UserFile.all().count() > FILE_MAX:
            oldest_file = UserFile.all().order('-creationDate').get()
            oldest_file.delete()
        #flush cache in order to update the file list
        memcache.flush_all()
        return HttpResponseRedirect(reverse(albumentry))

    else:
        filelist = UserFile.all().order('-creationDate').fetch(FILE_MAX)
        user = users.get_current_user()
        if user:
            sign_link = '<a href="%s">Logout</a>' % users.create_logout_url(reverse(albumentry))
        else:
            sign_link = '<a href="%s">Login</a>' % users.create_login_url(reverse(albumentry))
        displayFile=None
        if 'key' in request.REQUEST:
            displayFile=UserFile.get(request.REQUEST['key'])            
        template_values = {
            'displayFile':displayFile,               
            'user': user,
            'sign_link': sign_link,
            'filelist': filelist,
            'users':users,
            'form':FileForm(),
        }
        return render_to_response('upload/show_albumentry.html',template_values)
    
def show_albumentry(request,key):
    userfile = UserFile.get(key)
    filebin=userfile.filebin_set.get()
    if not userfile or not filebin:        
        return HttpResponseNotFound()
    return HttpResponse(filebin.bin,'image/JPEG')      

def download_albumentry(request,key):
    userfile = UserFile.get(key)
    filebin=userfile.filebin_set.get()
    if not userfile or not filebin:        
        return HttpResponseNotFound()
    response=HttpResponse(filebin.bin,userfile.mimetype)   

    #dealing with unicode :( Can't convert unicode to ascii when decode. 
    #If any solutions, please mail to me: lincong.javatech@gmail.com 
    if isinstance(userfile.name, unicode):
        response['Content-Type'] = 'application/octet-stream'
        encoding=sys.getdefaultencoding() 
        try :
            name=force_unicode(urllib.unquote(smart_str(userfile.name)))
            str=name.decode(encoding)
            filename=str.encode(encoding, 'replace')
            response['Content-Disposition'] = 'attachment; filename="%s"'%filename
        except UnicodeEncodeError:
            filename=userfile.name
            response['Content-Type']=userfile.mimetype 
    else:
        filename=userfile.name
        response['Content-Type']=userfile.mimetype 
    return response


def delete_albumentry(request,key):
    userfile = UserFile.get(key)
    if userfile.author==users.get_current_user() or users.is_current_user_admin():
        userfile.delete()
        #flush cache in order to update the file list
        memcache.flush_all()
        return HttpResponseRedirect(reverse(albumentry))
    else:
        return HttpResponseForbidden()
